<?php
namespace Home\Logic\OrderLogic;

use My\Model\OrderModel;
use My\Model\DistributionShopRateModel;
use Home\Logic\GoodsLogic;
use Utuo\DBRW;

/**
 * 普通订单业务类
 * @author song
 */
class Order implements IOrder { 
	
	/**
	 * 订单扩展属性
	 * @var array
	 */
	protected $orderExtendFields = array();
	
	/**
	 * 订单商品扩展属性
	 * @var array
	 */
	protected $orderGoodsExtendFields = array();
	
	/**
	 * 错误信息
	 * @var unknown
	 */
	protected $error = '';
	
	/**
	 * 客户id
	 * @var unknown
	 */
	protected $cid = 0;
	
	/**
	 * 用户id
	 * @var unknown
	 */
	protected $uid = 0;
	
	/**
	 * 用户数据
	 * @var unknown
	 */
	protected $user = null;
	
	/**
	 * 配置信息
	 * @var unknown
	 */
	protected $options = array(
		'cid' => 0, // 客户 id
	);
	
	/**
	 * 构造
	 */
	public function __construct( $options ) {
		$this->options = $options;
		$this->cid = $options['cid'];
		$this->uid = $options['uid'];
		if ( !$this->cid ) {
		    $this->error = "cid未设置";
		    throw new \Exception($this->error);
		}
		if ( !$this->uid ) {
		    $this->error = "uid未设置";
		    throw new \Exception($this->error);
		}
		$user = M("WechatUser")->where("cid=%d and id=%d", $this->cid, $this->uid)->find() and $this->user = $user;
	}
	
	/**
	 * 错误信息
	 */
	public function getError() {
		return $this->error;
	}
	
	
	/**
	 * 添加订单
	 * @param array $order
	 * array(18) {
	 *   ["create_time"] => int(1425201630)
	 *   ["order_no"] => string(22) "1503011720300000009100"
	 *   ["support_cod"] => int(0)
	 *   ["goods_amount"] => float(23213)
	 *   ["shipping_fee"] => int(10)
	 *   ["items"] => array(1) {
	 *     [1] => array(4) {
	 *       ["goods_type"] => int(0)
	 *       ["goods_id"] => int(1)
	 *       ["goods_name"] => string(12) "测试套餐"
	 *       ["items"] => array(1) {
	 *         [0] => array(5) {
	 *           ["goods_pic"] => string(72) "http://wmei-wmei5.stor.sinaapp.com/2014-12-16/2014121610531419015502.jpg"
	 *           ["goods_number"] => string(1) "1"
	 *           ["goods_price"] => string(8) "23213.00"
	 *           ["goods_attr"] => string(1) "-"
	 *           ["rate_status"] => int(0)
	 *         }
	 *       }
	 *     }
	 *   }
	 *   // 商品快照
	 *   ["snapGoods"] => array(1) {
	 *     [1] => array(20) {
	 *       ["id"] => string(1) "1"
	 *       ["cid"] => string(1) "1"
	 *       ["shipping_tpl_id"] => string(1) "0"
	 *       ["type"] => string(1) "1"
	 *       ["image"] => string(72) "http://wmei-wmei5.stor.sinaapp.com/2014-12-16/2014121610531419015502.jpg"
	 *       ["image_vertical"] => string(72) "http://wmei-wmei5.stor.sinaapp.com/2015-01-23/2015012314333017272507.jpg"
	 *       ["image_share"] => string(0) ""
	 *       ["config"] => string(0) ""
	 *       ["name"] => string(12) "测试套餐"
	 *       ["price"] => string(8) "23213.00"
	 *       ["saled_base"] => string(1) "0"
	 *       ["saled_count"] => string(1) "0"
	 *       ["shipping_method"] => string(1) "0"
	 *       ["shipping_config"] => array(3) {
	 *         [1] => string(2) "10"
	 *         [2] => string(2) "10"
	 *         [3] => string(1) "5"
	 *       }
	 *       ["sort"] => string(2) "11"
	 *       ["create_time"] => string(10) "1423192959"
	 *       ["status"] => string(1) "1"
	 *       ["is_deleted"] => string(1) "0"
	 *       ["images"] => array(1) {
	 *         [0] => string(72) "http://wmei-wmei5.stor.sinaapp.com/2014-12-16/2014121610531419015502.jpg"
	 *       }
	 *       ["attrs_cfg"] => array(0) {}
	 *     }
	 *   }
	 *   // 收货人信息部分
	 *   ["name"] => string(6) "宋义"
	 *   ["province"] => string(6) "230000"
	 *   ["city"] => string(6) "230200"
	 *   ["area"] => string(6) "230204"
	 *   ["address"] => string(15) "ewqrewqrewqrewq"
	 *   ["tel"] => string(11) "13849089206"
	 *   ["provinceName"] => string(12) "黑龙江省"
	 *   ["cityName"] => string(15) "齐齐哈尔市"
	 *   ["areaName"] => string(9) "铁锋区"
	 *   ["shipping_id"] => int(1)
	 *   // 配送费用
	 *   ["totalShipping"] => array(3) {
	 *     [1] => string(2) "10"
	 *     [2] => string(2) "10"
	 *     [3] => string(1) "5"
	 *   },
	 *   ["actual_cost"] => float(23223)
	 * }
	 */
	public function addOrder( $order, $payApitype ) {
	    // 商品快照
	    $snapGoods = $order['snapGoods'];
	    
		/* 保存订单 */
		$orderData = array (
		    'order_no' => $order['order_no'],
		    'cid' => $order['cid'],
		    'agent_id' => $order['agent_id'],
		    'uid' => $order['uid'],
		    'type' => $order['type'],
		    'actual_cost' => $order['actual_cost'],
		    'goods_amount' => $order['goods_amount'],
		    'shipping_fee' => $order['shipping_fee'],
		    'support_cod' => $order['support_cod'],
		    'order_status' => $order['order_status'],
		    'pay_status' => $order['pay_status'],
		    'consignee' => $order['consignee'],
		    'province' => $order['province'],
		    'city' => $order['city'],
		    'area' => $order['area'],
		    'address' => $order['address'],
		    'zipcode' => $order['zipcode'],
		    'tel' => $order['tel'],
		    'shipping_id' => $order['shipping_id'],
		    'create_time' => $order ['create_time'],
		    'confirm_time' => 0,
		    'shipping_time' => 0,
		);
		
		$d = D("Order");
		$orderId = $d->add($orderData);
		if ( $orderId ) {
		    /* 保存快照 */
		    $snapGoodsData = array();
		    foreach ( $snapGoods as $goods ) {
		        $snapGoodsData[] = array(
		            'order_id' => $orderId,
		            'goods_id' => $goods['id'],
		            'goods_data' => serialize($goods)
		        );
		    }
		    M("OrderGoodsSnap")->addAll($snapGoodsData);
		    /*  添加所有订单商品 */
		    $m = M ( "OrderGoods" );
		    $goodsList = array();
		    foreach ( $order['items'] as $goodsId => $goods ) {
		        $data = array(
		            'order_id' => $orderId,
		            'goods_type' => $goods['goods_type'],
		            'goods_id' => $goods['goods_id'],
		            'goods_name' => $goods['goods_name'],
		        );
		        foreach ( $goods['items'] as $v ) {
		            $data['goods_pic'] = $v['goods_pic'];
		            $data['goods_number'] = $v['goods_number'];
		            $data['goods_price'] = $v['goods_price'];
		            $data['goods_attr'] = $v['goods_attr'];
		        }
		        $goodsList[] = $data;
		    }
		    $firstId = $m->addAll($goodsList);
		    if ( $firstId ) {
		        $i = $firstId;
		        session ( "order", null );
		        $order['order_id'] = $orderId;
		        // 添加一维数组中的id
		        foreach ( $goodsList as &$v ) {
	                $v['order_goods_id'] = $i;
	                $i++;
		        }
		        // 添加二维数组中的id
		        $i = $firstId;
		        foreach ( $order['items'] as $goodsId => &$goods ) {
		            foreach ( $goods['items'] as &$v ) {
		                $v['order_goods_id'] = $i;
		                $i++;
		            }
		        }
		        $this->addExtends( $order, $goodsList );
		        return $orderId;
		    }
		}
		return 0;
	}

	/**
	 * 订单id
	 * @param int $orderId
	 * @return
	 */
	public function getOrder( $orderId ) {
		/* 订单数据库中一条订单的关联数据 */
		$order = $this->getOne($orderId);
		/* 绑定订单详细  */
		$this->bindOrdersDetail ( $order );
		return $order;
	}
	
	/**
	 * 绑定订单详细
	 */
	public function bindOrdersDetail( &$orders ) {
		if ( !$orders ) return;  
		$data = '';
		reset($orders);
		if ( is_numeric(key($orders)) and key($orders) == 0 ) {
			$data = &$orders;
		} else {
			$data[] = &$orders;
		}
		foreach ( $data as $k => &$order ) {
		    /* 绑定买家操作 */
		    $this->bindOrderOperateForBuyer($order);
		    /* 绑定订单显示状态 */
		    $this->bindOrderShowStatus( $order );
			/* 绑定订单商品 */
			$this->bindOrderGoods( $order );
			/* 订单商品快照 */
			$goodsList = M("orderGoodsSnap")->where("order_id=%d", $order['id'])->getField('goods_id,goods_data');
			foreach ( $goodsList as $k => $v ) {
			    $goodsList[$k] = unserialize($v);
			}
			$order['snapGoods'] = $goodsList;
		}
	}
	
	/**
	 * 获得欲保存订单
	 * @param $options
	 * array(
	 *   'agentId' => 1,  // 购买时的代理商id
	 * 	 'goods' => array(
	 * 		 '1(产品id)' => array(
	 * 		    '属性名1|值1,属性名2|值2' => array(
	 * 			   'quantity' => 1,
	 * 		    ),
	 * 		 )
	 * 	  ),
	 * 	  'crtId' => array( '1225455', '58756645', '45587156', ), // 购物车中的商品id
	 * )
	 * @param 
	 */
	public function getSaveingOrder( $options ) {
		$agentId = $options['agentId'];
		$goods = $options['goods'];
		$crtId = $options['crtId'];
		/* 验证订单商品 */
		$goodsList = array(); // 购买的商品列表
		$submitGoods = array(); // 用户提交时的订单商品数据
		if ( $goods ) { // 非购物车数据
			if ( $this->checkSavingOrderGoods($goods, $goodsList) ) {
				$submitGoods = $goods;
			} else {
				return false;
			}
		} elseif ( $crtId ) { // 购物车数据
			//... ...
		}
		/* 默认收货地址 */
		$address = $this->getAddress(0, 1);
		/* 获得订单保存时的结构数组(与getOrder方法返回结构相同) */
		$totalPrice = 0; // 总价
		$totalShpping = array(); // 总运费列表
		$supportCod = 1; // 默认支持货到付款
		$orderItems = array(); // 欲保存订单商品
		foreach ( $submitGoods as $goodsId => $goodsItems ) {
			$buyGoods = $goodsList[$goodsId]; // 交易时的商品
			$count = 0; // 购买数量
			$subtotal = 0; // 小计
			/* 判断订单中每件商品是否支持货到付款，从而求出整个订单是否支持货到付款  */
			if ( !$buyGoods['support_cod']*1 ) $supportCod = 0;
			foreach ( $goodsItems as $attrStr => $attrItem ) {
				$orderItems[$goodsId] or $orderItems[$goodsId] = array(
					'goods_type' =>  isset($buyGoods ['type']) ? $buyGoods ['type'] : OrderModel::ORDER_TYPE_COMMON,
					'goods_id' => $goodsId,
					'goods_name' => $buyGoods ['name'],
					'items' => array(),
				);
				$quantity = $attrItem ['quantity'];
				$price = $buyGoods ['take_price'];
				$attrItemTmp = array(
					'goods_pic' => $buyGoods ['images'][0],
					'goods_number' => $quantity,
					'goods_price' => $price,
					'goods_attr' => $attrStr,
					'rate_status' => DistributionShopRateModel::RATE_STATUS_UNRATE,
				) and $orderItems[$goodsId]['items'][] = &$attrItemTmp;
				$count += $quantity;
				$subtotal += $price * $quantity;
			}
			$totalPrice += $subtotal;
		}
		
		$order = array (
		    'order_no' => date ( "ymdHis" ) . str_pad ( $this->sid, 6, 0, STR_PAD_LEFT ) . rand ( 1000, 9999 ), // 订单号
		    'cid' => $this->cid,
		    'agent_id' => $agentId,
		    'uid' => $this->uid,
		    'type' => OrderModel::ORDER_TYPE_COMMON,
			'create_time' => time (),
			'support_cod' => $supportCod,
			'goods_amount' => $totalPrice,
			'shipping_fee' => 0.00,
			'items' => $orderItems,
		    'snapGoods' => $goodsList,
		    'order_status' => OrderModel::ORDER_STATUS_PAY,
		    'pay_status' => OrderModel::PAY_STATUS_NOT_PAID,
		);
		
		/* 附加收货地址数据 */
		$this->bindAddress( $order, $address, 1 );
		/* 附加运费信息 */
		$this->bindShipping( $order );
		/* 实际消费总额 */
		$order['actual_cost'] = $order ['goods_amount'] + $order ['shipping_fee'];
		/* 绑定扩展信息 */
		$this->bindExtends( $order );
		/* 绑定买家操作 */
		$this->bindOrderOperateForBuyer($order);
		/* 绑定订单显示状态  */
		$this->bindOrderShowStatus($order);
		return $order;
	}
	
	/**
	 * 获得预付款订单
	 * @param $orderId 订单id
	 * @param $options 
	 * array(
	 * 	 'addressId' => '1247',
	 * )
	 */
	public function getPayingOrder( $orderId, $options ) {
		$order = $this->getOrder($orderId);
		if ( $order ) {
			$cid = $order['cid'];
			$addressId = $options['addressId'];
			/* 订单商品快照 */
			$goodsList = M("orderGoodsSnap")->where("order_id=%d", $orderId)->getField('goods_id,goods_data');
			foreach ( $goodsList as $k => $v ) {
			    $goodsList[$k] = unserialize($v);
			}
			$order['snapGoods'] = $goodsList;
			/* 收货地址 */
			$this->bindAddress( $order, $addressId, 0 );
			/* 附加运费信息 */
			$this->bindShipping($order);
			return $order;
		}
		return null;
	}
	
	/**
	 * 订单数据库中一条订单的关联数据
	 */
	public function getOne( $orderId ) {
	    $condition = array(
	        "orders.id" => $orderId,
	    );
	    $order = M ( "Order orders" )->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
                            	    ->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
                            	    ->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
                            	    ->field ( "orders.*,province.name as provinceName, city.name as cityName, area.name as areaName" )
                            	    ->where ( $condition )
                            	    ->find ();
	    return $order;
	}
	
	/**
	 * 获得订单列表
	 * @param unknown $condition
	 * @return unknown
	 */
	public function getList( $condition ) {
	    $m = M ( "Order orders" );
	    $orderLists = $m->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
                	    ->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
                	    ->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
                	    ->field ( "orders.*,province.name as provinceName, city.name as cityName, area.name as areaName" )
                	    ->where ( $condition )->order("orders.id desc")
                	    ->select ();
	    return $orderLists;
	}
	
	
	/**
	 * 验证提交的商品属性（用于购买与加入购物车时的验证）
	 * @param array $goods
	 * 	 'goods' => array(
	 * 		 '1(产品id)' => array(
	 * 		    '属性名1|值1,属性名2|值2' => array(
	 * 			   'quantity' => 1,
	 * 		    ),
	 * 		 )
	 * 	  ),
	 * @param  &array $goodsList 购买的商品列表
	 * @return boolean
	 */
	protected function checkSavingOrderGoods( $goods, &$goodsList = array() ) {
		foreach ( $goods as $goodsId => $goodsItems ) {
			$goodsOne = $this->getBuyGoodsOne( $goodsId );
			if ( !$goodsOne ) {
				$this->error = '商品已不存在~';
				return false;
			}
			$attrsCfg = $goodsOne['attrs_cfg'];
			foreach ( $goodsItems as $attrStr => $attrItem ) {
				/* 商品已选择的属性与属性值  */
				$selectedAttrs = array();
				if ( $attrStr and ($attrStr != '-') ) {
					foreach ( explode(',', $attrStr) as $attrItemStr ) {
						list($selAttrName, $selAttrValue) = explode('|', $attrItemStr);
						$selectedAttrs[$selAttrName] = $selAttrValue;
					}
				}
				/* 检查商品属性选择 */
				foreach ( $attrsCfg as $k => $v ) {
					$v = (array)$v;
					if(!isset($selectedAttrs[$k])) {
						$this->error = "属性:{$k}未选择.";
						return false;
					}
					if(!in_array($selectedAttrs[$k], $v)) {
						$this->error = "属性值:{$selectedAttrs[$k]}未找到.";
						return false;
					}
				}
			}
			$goodsList[$goodsId] = $goodsOne;
		}
		return true;
	}
	
	/**
	 * 绑定订单商品
	 * @param unknown $orderGoodsDao
	 * @param unknown $order
	 */
	protected function bindOrderGoods( &$order ) {
		$orderGoodsList = $this->getOrderGoodsList($order['id']);
		foreach ( $orderGoodsList as &$v0 ) {
			$order ['items'] [$v0 ['goods_id']] or $order ['items'] [$v0 ['goods_id']] = array (
				'goods_type' => $v0 ['goods_type'],
				'goods_id' => $v0 ['goods_id'],
				'goods_name' => $v0 ['goods_name'],
				'items' => array (),
			);
			$data = array (
					'order_goods_id' => $v0 ['id'],
					'goods_pic' => $v0 ['goods_pic'],
					'goods_number' => $v0 ['goods_number'],
					'goods_price' => $v0 ['goods_price'],
					'goods_attr' => $v0 ['goods_attr'],
					'rate_status' => $v0 ['rate_status'],
			);
			/* 订单商品字段扩展  */
			foreach ( $this->orderGoodsExtendFields as $v ) {
				$data[$v] = $v0[$v];
			}
			$order ['items'] [$v0 ['goods_id']] ['items'] [$v0 ['id']] = $data;
		}
	}
	
	/**
	 * 获得买家订单操作
	 */
	protected function getOrderOperateForBuyer( $order ) {
	    $status = $order['order_status'];
	    $payStatus = $order['pay_status'];
	    $operates = array();
	    if ( empty($order['id']) ) {
	        $operates[] = "pay";
	    } elseif( $order['pay_method'] != 'COD' and $status == OrderModel::ORDER_STATUS_PAY  ) {
	        $operates[] = "pay";
	        $operates[] = "cancel";
	        if ( $order['buy_method'] == OrderModel::BUY_METHOD_COMMON ) {
	            $operates[] = "startPayAnother"; // 发起代付
	        }
	    } elseif( $status == OrderModel::ORDER_STATUS_SHIPPING ) {
	        $operates[] = "refund"; // 退款
	    } elseif ( $status == OrderModel::ORDER_STATUS_SIGN ) {
	        $operates[] = "sign";
	    } elseif ( $status == OrderModel::ORDER_STATUS_COMPLETED ) {
	        $operates[] = "rate";
	    }
	    return $operates;
	}
	
	/**
	 * 获得订单显示状态
	 * @param array $order
	 * @return string
	 */
	public function getOrderShowStatus( $order ) {
	    $status = $order['order_status'];
	    $payStatus = $order['pay_status'];
	    $statusText = "";
	    if(isset(OrderModel::$ORDER_STATUS[$status])) {
	        if(!$payStatus and ($status == OrderModel::ORDER_STATUS_SHIPPING or $status == OrderModel::ORDER_STATUS_SIGN)) {
	            $statusText = OrderModel::$ORDER_STATUS[$status]."(货到付款)";
	        } else {
	            $statusText =  OrderModel::$ORDER_STATUS[$status];
	        }
	    } else {
	        $statusText = OrderModel::$ORDER_STATUS[0];
	    }
	    return $statusText;
	}
	
	/**
	 * 绑定买家订单显示状态
	 * @param unknown $order
	 * @return NULL
	 */
	protected function bindOrderShowStatus( &$order ) {
	    if( is_array($order) ) {
	        $list = array();
	        reset($order);
	        if ( !is_numeric(key($order)) ) {
	            $list[] = &$order;
	        } else {
	            $list = &$order;
	        }
	        foreach ( $list as $k => &$v ) {
	            $v['orderStatusName'] = $this->getOrderShowStatus($v);
	        }
	    }
	    return null;
	}
	
	
	/**
	 * 绑定买家订单操作
	 * @param unknown $order
	 * @return NULL
	 */
	protected function bindOrderOperateForBuyer( &$order ) {
	    if( is_array($order) ) {
	        $list = array();
	        reset($order);
	        if ( !is_numeric(key($order)) ) {
	            $list[] = &$order;
	        } else {
	            $list = &$order;
	        }
	        foreach ( $list as $k => &$v ) {
	            $v['buyerOperates'] = $this->getOrderOperateForBuyer($v);
	        }
	    }
	    return null;
	}
	
	/**
	 * 获得订单收货地址信息
	 * @param $addressId 收货地址id
	 * @param $auto 无收货地址id时自动寻找默认
	 * @return array
	 * array(
	 * 		'id' => 1,
	 * 		'consignee' => '',
	 * 		'province' => 11000,
	 * 		'city' => 11100,
	 * 		'area' => 11101,
	 * 		'address' => '',
	 * 		'tel' => '',
	 * 		'provinceName' => '',
	 * 		'cityName' => '',
	 * 		'areaName' => '',
	 * )
	 */
	protected function getAddress( $addressId = 0, $auto = 1 ) {
		$condition = array(
			'address.uid' => $this->uid,
		);
		if ( $addressId ) {
			$condition['address.id'] = $addressId;
		} elseif ( !$auto ) {
			return null;
		} else {
			$condition['address.status'] = 1;
		}
		$address = M ( "DistributionShopDeliverAddress address" )->join ( "__CN_PROVINCE__ province on address.province = province.code", "LEFT" )
						->join ( "__CN_CITY__ city on address.city = city.code", "LEFT" )
						->join ( "__CN_AREA__ area on address.area = area.code", "LEFT" )
						->field ( "address.*,province.name as provinceName, city.name as cityName, area.name as areaName" )
						->where ( $condition )
						->order ( "address.status desc" )
						->find ();
		return $address;
	}
	
	/**
	 * 获得订单商品列表关联数据
	 * @param unknown $orderId
	 */
	protected function getOrderGoodsList( $orderId ) {
		return M("OrderGoods")->where ( "order_id=%d", $orderId )->select ();
	}
	
	/**
	 * 获得一个购买时的商品
	 * @param unknown $goodsId
	 * @return mixed
	 * array(
	 * 	 'take_price' => '0.00', // 拍下价格
	 * 	 // ... ...
	 * )
	 */
	protected function getBuyGoodsOne( $goodsId ) {
		$m = M("DistributionShopGoods");
		$goodsOne = $m->where('cid=%d and id=%d', $this->cid, $goodsId)->find();
		if ( $goodsOne ) {
			$goodsOne['images'] = unserialize($goodsOne['images']);
			$goodsOne['attrs_cfg'] = $attrs_cfg = ($goodsOne['attrs_cfg'] ? unserialize($goodsOne['attrs_cfg']) : array());
			/* 拍下价格处理 */
			$goodsOne['take_price'] = $goodsOne['price'];
		}
		return $goodsOne;
	}
	
	/**
	 * saveing 时绑定订单扩展与修改订单数据信息
	 * @param unknown $order
	 */
	protected function bindExtends( &$order ) {}
	
	/**
	 * 添加订单扩展信息
	 * @param $order 订单关联数组(含order_id) 
	 * @param $goodsList 订单商品一维数组(含order_goods_id) $order
	 */
	protected function addExtends( $order, $goodsList ) {}
	
	
	/**
	 * 绑定收货地址
	 * @param unknown $order
	 * @param number $addressId
	 * @param number $auto
	 */
	private function bindAddress( &$order, $addressId = 0, $auto = 1 ) {
	    if ( is_array($addressId) ) {
	        $address = $addressId;
	    } else {
	        $address = $this->getAddress($addressId, $auto);
	    }
	    if ( $address ) { // 将当前设置的地址信息写入订单
	        foreach ( array( 'name', 'province', 'city', 'area', 'address', 'tel', 'provinceName', 'cityName', 'areaName' ) as $v ) {
	            $order[$v == 'name' ? 'consignee' : $v] = $address[$v];
	        }
	    }
	}

	/**
	 * 绑定运费信息
	 * @param array $order 订单对象
	 * @param array $goodsList 当前购买的商品列表(即getBuyGoodsOne方法获得的商品，其中是否需要配送/默认配送方式/配送价格必须)
	 */
	private function bindShipping( &$order ) {
	    $goodsList = $order['snapGoods'];
	    $totalShipping = array();
	    foreach ( $order['items'] as $goodsId => $goods ) {
	        $goodsOne = $goodsList[$goodsId]; // 购买时商品的快照
	        $count = 0;
			foreach ( $goods['items'] as $attrGoodsItem ) {
                $count += $attrGoodsItem['goods_number'];
			}
			if ( $goodsOne['shipping_tpl_id']*1 ) { // 有运费模板时
			    /* 计算运费 */
			    $shippingPriceList = GoodsLogic::calcDeliveryFee(array('tplId'=>$goodsOne['shipping_tpl_id']), $order['province'], $count);
			    /* 汇总运费 */
			    foreach ( $shippingPriceList as $k => $v ) {
			        $totalShipping[$k] += $v;
			    }
			} else { // 无运费模板时
			    if( $goodsOne['shipping_config'] ) {
			        foreach ($goodsOne['shipping_config'] as $k => $v) {
			            $v*1 and $totalShipping[$k] += $v*$count;
			        }
			    }
			}
	    }
	    $shippingId = $order['shipping_id'];
        $order['shipping_id'] = $shippingId ? $shippingId : key($totalShipping)*1; // 用户要求配送方式 1.快递 2.EMS 3.平邮
        $order['shipping_fee'] = $shippingId ? $totalShipping[$shippingId] : current($totalShipping)*1;
	    $order['totalShipping'] = $totalShipping;
	}
	
	/**
	 * 订单签收
	 * @param int $orderId 订单
	 * @return array 订单表一维数组
	 */
	public function confirmSign( $orderId ) {
	    $d = M ( "Order" );
	    DBRW::openAndClose(0);
	    $order = $this->getOne( $orderId );
	    DBRW::openAndClose(1);
	    if($order['order_status'] == OrderModel::ORDER_STATUS_SIGN) {
	        // 更新订单状态
	        $data = array("order_status" => OrderModel::ORDER_STATUS_COMPLETED,
	            "take_time" => time(),
	            "deal_time" => time(),);
	        if( false !== $d->where ( array ( "uid" => $this->uid, "id" => $orderId, ) )
	                        ->save ( $data ) ) {
                 $order = array_merge($order, $data);
                 method_exists($this, "afterOrderCompleted") and $this->afterOrderCompleted( $order );
                 return $order;
	        }
	    } else {
	        $this->error = "非已发货状态，不能完成收货操作。";
	    }
	    $this->error = "提交失败，请重新确认收货";
	    return false;
	}
	
}